//!@author denglibin
//!@date 2025/11/3 10:17
//!@desc api示例 地址 https://www.mongodb.com/zh-cn/docs/drivers/rust/current/fundamentals/connections/connection-guide/

use crate::component::mongo::mongo_doc::Book;
use mongodb::options::Credential;
use mongodb::{bson::doc, options::{ClientOptions, ServerApi, ServerApiVersion}, Client, Collection};

const DB_NAME: &str = "my_doc_2";

pub async fn connect() -> mongodb::error::Result<()> {
    // Replace the placeholder with your Atlas connection string
    let uri = "mongodb://192.168.6.170:27017";
    let mut client_options = ClientOptions::parse(uri).await?;

    //账号密码
    let default_cred = Credential::builder()
        .username("mongo".to_string())
        .password("mongo".to_string())
        .build();
    client_options.credential = Some(default_cred);


    // Set the server_api field of the client_options object to Stable API version 1
    let server_api = ServerApi::builder().version(ServerApiVersion::V1).build();
    client_options.server_api = Some(server_api);

    // Create a new client and connect to the server
    let client = Client::with_options(client_options)?;

    // Send a ping to confirm a successful connection
    client.database(DB_NAME).run_command(doc! { "ping": 1 }).await?;
    println!("Pinged your deployment. You successfully connected to MongoDB!");

    //数据库列表
    let db_list = client.list_database_names().await?;
    println!("数据库:{:?}", db_list);

    let db = client.database(DB_NAME);
    //创建集合
    // db.create_collection("coll_abc").await?;

    let coll_list = db.list_collection_names().await?;
    println!("集合:{:?}", coll_list);


    let my_coll: Collection<Book> = db.collection("coll_abc");

    //添加文档
    let docs = vec![
        Book {
            _id: 5,
            title: "Cat's Cradle".to_string(),
            author: "Kurt Vonnegut Jr.".to_string()
        },
        Book {
            _id: 6,
            title: "In Memory of Memory".to_string(),
            author: "Maria Stepanova".to_string()
        },
        Book {
            _id: 7,
            title: "Pride and Prejudice".to_string(),
            author: "Jane Austen".to_string()
        }
    ];

    let insert_many_result = my_coll.insert_many(docs).await?;
    println!("Inserted documents with _ids:");
    for (_key, value) in &insert_many_result.inserted_ids {
        println!("{:?}", value);
    }



    Ok(())
}
